const PENDING = 'pending'
const FULFILLED = 'fullfilled'
const REJECTED = 'rejected'
class myPromise {
    constructor(executor) {
        this.state = PENDING;
        this.value = undefined;
        this.reason = undefined;

        this.onFulfilledcb = [] //定义一个数组，用来存储成功的回调函数
        this.onRejectedcb = []  //定义一个数组，用来存储失败的回调函数

        let resolve = (value) => {
            if (this.state === PENDING) {
                this.state = FULFILLED;
                this.value = value;
                this.onFulfilledcb.forEach(cb => cb()) 
            }
        }
        let reject = (reason) => {
            if (this.state === PENDING) {
                this.state = REJECTED;
                this.reason = reason;
                this.onRejectedcb.forEach(cb => cb())
            }
        }
        try {
            executor(resolve, reject)
        } catch (error) {
            reject(error)
        }
    }
    then(onFulfilled, onRejected) {
        if (this.state === FULFILLED) {
            onFulfilled(this.value)
        }
        if (this.state === REJECTED) {
            onRejected(this.reason)
        }
        if (this.state === PENDING) {  //如果promise是等待状态，就把函数存起来
            this.onFulfilledcb.push(() => {
                onFulfilled(this.value)
            })
            this.onRejectedcb.push(() => {
                onRejected(this.reason)
            })
        }

    }
}
let promise = new myPromise((resolve, reject) => {
    setTimeout(() => {
        resolve("jjj")
    }, 2000)
})

promise.then((data) => {
    console.log("data1" + data);
}, (err) => {
    console.log("err1" + err);
})

promise.then((data) => {
    console.log("data2" + data);
}, (err) => {
    console.log("err2" + err);
})